package leetcode.t1Array;

import java.util.Arrays;

/**
 * @author K
 * @date 2024/1/19 14:22
 */
public class T16_ThreeSumClosest {

    /**
     * 16. 最接近的三数之和
     * n数之和，最多n-1次循环
     */
    public static int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int length = Integer.MAX_VALUE;
        int result = 0;
        go:
        for (int i = 0; i < nums.length - 2; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            int l = i + 1, r = nums.length - 1;
            while (l < r) {
                int sum = nums[i] + nums[l] + nums[r];
                if (sum > target) {
                    r--;
                } else if (sum < target) {
                    l++;
                } else {
                    while (l < r && nums[l] == nums[l + 1]) l++;
                    while (l < r && nums[r] == nums[r - 1]) r--;
                    l++;
                    r--;
                    result = target;
                    break go;
                }
                int newLength = Math.abs(target - sum);
                if (newLength <= length) {
                    length = newLength;
                    result = sum;
                }
            }
        }

        return result;
    }

    public static void main(String[] args) {
        int[] nums = {-1, 2, 1, -4};
        int result = T16_ThreeSumClosest.threeSumClosest(nums, 1);
//        int result2 = T16_ThreeSumClosest.threeSumClosest(new int[]{0,0,0}, 1);
        int result2 = T16_ThreeSumClosest.threeSumClosest(new int[]{1,1,1,1}, 3);
        System.out.println();
    }
}
